package org.fuys.coder.application;

import lombok.extern.slf4j.Slf4j;
import org.fuys.coder.common.entity.Pair;
import org.fuys.coder.common.entity.Result;
import org.fuys.coder.common.constants.ResultMessageConstants;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.common.holder.UserHolder;
import org.fuys.coder.domain.auth.model.vo.UserVo;
import org.fuys.coder.common.entity.PageDTO;
import org.fuys.coder.domain.favorites.model.vo.FavoritesIntroVO;
import org.fuys.coder.domain.favorites.service.IFavoriteService;
import org.fuys.coder.domain.mailbox.model.vo.MailVO;
import org.fuys.coder.domain.mailbox.service.IMailBoxService;
import org.fuys.coder.domain.model.service.IUserModelService;
import org.fuys.coder.domain.substance.model.vo.SubstanceVO;
import org.fuys.coder.domain.substance.service.repo.ISubstanceService;
import org.fuys.coder.domain.user.model.req.repo.UserInfoUpdateReq;
import org.fuys.coder.domain.user.model.vo.repo.AuthorVO;
import org.fuys.coder.domain.user.service.repo.IUserService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.application
 * @className: UserController
 * @author: WangJing
 * @description: 用户相关信息控制器 如内容信息 个人信息 收藏夹信息等
 * @date: 2024/7/3 22:15
 * @version: 1.0
 */

@Slf4j
@RestController
@RequestMapping("/fuyscoder/userinfo")
public class UserInfoController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserModelService userModelService;

    @Resource
    private IMailBoxService mailBoxService;

    @Resource
    private ISubstanceService substanceService;

    @Resource
    private IFavoriteService favoriteService;

    @PostMapping("/update")
    public Result updateInfo(@RequestBody UserInfoUpdateReq updateReq){
        final Integer userid = UserHolder.get();
        if(ObjectUtils.isEmpty(userid)){
            throw new BusinessException(ResultMessageConstants.NO_USER_TOKEN);
        }
        String msg=ResultMessageConstants.USER_UPDATE_SUCCESS;
        try {
            userService.updateUserInfo(updateReq, userid);
        } catch (BusinessException e) {
            e.printStackTrace();
            msg=ResultMessageConstants.USER_UPDATE_FAILED;
        }
        return Result.ok().msg(msg);
    }

    @GetMapping("/info/{userId}")
    public Result getInfoById(@PathVariable Integer userId){
        //因为这里是获取的个人信息 所以对于任何人都是可以展示的
        UserVo userVo=userService.getUserInfo(userId);
        return Result.ok().data(userVo);
    }

//    @PostMapping("/model/update")
//    public void updateModel()  {
//        //todo 怎么忽略Broken pipe这个IO异常呢？
//        final Integer integer = UserHolder.get();
//        if(ObjectUtils.isEmpty(integer)){
//            return;
//        }
//        userModelService.enduranceUserModel(integer);
//    }

    @PostMapping("/inbox")
    public Result getInboxInfo(){
        final Integer userId = UserHolder.get();
        if(ObjectUtils.isEmpty(userId)){
            throw new BusinessException(ResultMessageConstants.NO_USER_TOKEN);
        }
        List<MailVO> userInbox=null;
        try {
            userInbox = mailBoxService.getUserInbox(userId);
        } catch (Exception e) {
            return Result.error("获取信箱内容失败 请稍后再试");
        }
        return Result.ok().data(userInbox);
    }

    @PostMapping("/favInfo/{userId}")
    public Result getFavInfo(@PathVariable(value = "userId")Integer userId){
        List<FavoritesIntroVO> favInfos = null;
        try {
            List<Long> ids = userService.getUserFavIds(userId);
            //判断是否是用户本人进行操作 是则展示隐私(true) 否则不展示(false)
            final boolean equals = userId.equals(UserHolder.get());
            favInfos = favoriteService.selectFavInfo(ids,equals);
        } catch (BusinessException e) {
            return Result.error(e.getMsg());
        } catch (Exception e){
            return Result.error(ResultMessageConstants.SYSTEM_ERROR);
        }
        return Result.ok().data(favInfos);
    }


    @PostMapping("/substances/{userId}")
    public Result getUserSubstances(@PathVariable(value = "userId")Integer userId,
                                    @RequestBody PageDTO pageDTO){
        List<SubstanceVO> substanceVOList=null;
        if(ObjectUtils.isEmpty(UserHolder.get())||!UserHolder.get().equals(userId)){
            substanceVOList=substanceService.getAuthorSubstancesByOpenFlag(userId,pageDTO,false);
        }else {
            substanceVOList = substanceService.getAuthorSubstancesByOpenFlag(userId,pageDTO,true);
        }
        return Result.ok().data(substanceVOList);
    }

    @PostMapping("/concern/{userId}")
    public Result getUserConcern(@PathVariable(value = "userId")Integer userId,
                                 @RequestBody PageDTO pageDTO){
        List<AuthorVO> authorList=null;
        if(ObjectUtils.isEmpty(pageDTO)){
            return Result.error(ResultMessageConstants.ILLEGAL_OPERATION);
        }
        authorList=userService.getUserConcernVos(userId,pageDTO);
        return Result.ok().data(authorList);
    }

    @PostMapping("/fans/{userId}")
    public Result getUserFollowers(@RequestParam("type")Integer type,
                                   @PathVariable(value = "userId")Integer userId,
                                   @RequestBody PageDTO pageDTO){
        List<AuthorVO> authorList=null;
        if(ObjectUtils.isEmpty(pageDTO)){
            return Result.error(ResultMessageConstants.ILLEGAL_OPERATION);
        }
        authorList=userService.getUserFollowerVos(userId,type,pageDTO);
        return Result.ok().data(authorList);
    }

    @PostMapping("/favorites/{userId}/{favId}")
    public Result getUserFavContent(@PathVariable(value = "userId")Integer userId,
                                    @PathVariable(value = "favId")Long favId,
                                    @RequestBody PageDTO pageDTO){
        try {
            if(userService.checkFavBelongUser(userId,favId)){
                Pair<List<Long>, Long> idList = favoriteService.selectPageByFavId(favId,pageDTO);
                if(ObjectUtils.isEmpty(idList)){
                    return Result.ok();
                }
                final List<SubstanceVO> substanceList = substanceService.getSubstanceList(idList.getLeft());
                return Result.ok().data(new Pair<>(substanceList,idList.getRight()));
            }else{
                return Result.error(ResultMessageConstants.ILLEGAL_OPERATION+":请查看您自己的收藏夹");
            }
        } catch (BusinessException e) {
            return Result.error(e.getMsg());
        } catch (Exception e){
            e.printStackTrace();
            return Result.error(ResultMessageConstants.SYSTEM_ERROR);
        }
    }
}
